/**
 *
 */
package per.vic.attachment.service;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import per.vic.attachment.autoconfigure.AttachmentProperties;
import per.vic.attachment.constant.AttachmentConstant;
import per.vic.attachment.model.Attachment;
import pers.vic.boot.base.craw.BaseCrawl;
import pers.vic.boot.base.craw.CrawlConnect;
import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.util.CommonUtils;
import pers.vic.boot.util.JsonUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 *  @description: 和附件服务端交互的接口, 附件客户端使用
 *  @author Vic.xu
 *  @date: 2020年9月18日下午4:04:33
 */
public class AttachmentClientService extends BaseCrawl {

    private static Logger logger = LoggerFactory.getLogger(AttachmentClientService.class);

    @Autowired
    private AttachmentProperties attachmentProperties;

    /**
     * 上传文件到附件服务端
     * @param fileName 文件名
     * @param in 文件流
     * @param module 模块
     */
    public BaseResponse<Attachment> uploadToServer(String fileName, InputStream in, String module) {
        logger.info("上传文件到文件服务器：文件名[{}],模块名[{}]", fileName, module);
        BaseResponse<Attachment> r = BaseResponse.error();
        String url = attachmentProperties.getServer() + "/attachment/temporary/upfile";
        try {
            CrawlConnect connect = con(url);
            setHeader(connect);
            String text = connect.data("upfile", fileName, in).data("module", module).postBodyText();
            r = JsonUtil.jsonToObject(text, new TypeReference<BaseResponse<Attachment>>() {
            });
        } catch (IOException e) {
            r.setMsg(e.getMessage());
            logger.error("上传文件到文件服务器出错了", e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        return r;
    }

    /**
     * 修改附件状态
     * @param temporary 是否为临时态
     * @param ids id数组
     */
    public boolean updateTemporary(boolean temporary, Integer... ids) {
        if (ids.length <= 0) {
            return true;
        }
        ids = CommonUtils.deleteNullInArr(ids);
        if (ids.length == 0) {
            return true;
        }

        logger.info("修改附件{}的状态为{}", ids, temporary);
        try {
            CrawlConnect connect = getConnect(AttachmentConstant.API_URL_ATTACHMENT_BATCH_UPDATE);
            setHeader(connect);
            String text = connect.data("ids", StringUtils.join(ids, "-")).
                    data("temporary", String.valueOf(temporary)).postBodyText();
            BaseResponse<?> r = JsonUtil.jsonToObject(text, new TypeReference<BaseResponse<?>>() {
            });
            if (r.getCode() == 0) {
                return true;
            } else {
                logger.warn("修改附件状态失败[{}]", r.getMsg());
            }
        } catch (IOException e) {
            logger.error("修改附件的状态出错了", e);
        }
        return false;
    }

    /**
     * 查询单个附件的详情
     * @param id id
     * @return detail
     */
    public BaseResponse<Attachment> findAttachmentById(int id) {
        if (id <= 0) {
            return BaseResponse.success();
        }
        CrawlConnect connect = getConnect(AttachmentConstant.API_URL_ATTACHMENT_DETAIL);
        try {
            String text = connect.data("id", String.valueOf(id)).postBodyText();
            BaseResponse<Attachment> attachment = JsonUtil.jsonToObject(text, new TypeReference<BaseResponse<Attachment>>() {
            });

            return attachment;
        } catch (IOException e) {
            logger.error("获取附件详情出错了", e);
        }
        return BaseResponse.error("获取附件详情失败");
    }

    /**
     * 查询多个附件详情
     * @param ids   ids
     * @return details
     */
    public BaseResponse<List<Attachment>> findAttachmentsByIds(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return BaseResponse.success();
        }
        CrawlConnect connect = getConnect(AttachmentConstant.API_URL_ATTACHMENT_DETAILS);
        try {
            String text = connect.data("ids", StringUtils.join(ids, "-")).postBodyText();
            BaseResponse<List<Attachment>> attachments = JsonUtil.jsonToObject(text, new TypeReference<BaseResponse<List<Attachment>>>() {
            });
            return attachments;
        } catch (IOException e) {
            logger.error("获取附件列表出错了", e);
        }
        return BaseResponse.error("获取附件列表失败");

    }

    /**
     * 根据url获得CrawlConnect
     * @param url 相对url
     * @return CrawlConnect
     */
    private CrawlConnect getConnect(String url) {
        String serverUrl = attachmentProperties.getServer();
        url = serverUrl + url;
        CrawlConnect connect = con(url);
        setHeader(connect);
        return connect;
    }

    /**
     * 设置header信息由于验证是否可访问附件项目
     */
    private void setHeader(CrawlConnect connect) {
        connect.header(AttachmentProperties.HEADER_CHECK_NAME, attachmentProperties.getPassword());
    }

    @Override
    protected int getTimeout() {
        return 50000;
    }
}
